<template>
  <ElDialog
    v-model="visible"
    :title="isEdit ? '编辑新就业人群' : '新增新就业人群'"
    width="800px"
    top="4vh"
    :close-on-click-modal="false"
    @open="handleOpen"
    @close="handleClose"
  >
    <ElForm ref="formRef" :model="form" :rules="rules" label-width="120px" label-position="right">
      <ElRow :gutter="20">
        <ElCol :span="12">
          <ElFormItem label="姓名" prop="newName">
            <ElInput
              v-model="form.newName"
              placeholder="请输入姓名"
              maxlength="30"
              show-word-limit
              :disabled="isView"
            />
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="手机号" prop="newPhone">
            <ElInput
              v-model="form.newPhone"
              placeholder="请输入手机号"
              maxlength="11"
              :disabled="isView"
            />
          </ElFormItem>
        </ElCol>
      </ElRow>

      <ElRow :gutter="20">
        <ElCol :span="12">
          <ElFormItem label="身份证号" prop="newIdentity">
            <ElInput
              v-model="form.newIdentity"
              placeholder="请输入身份证号"
              maxlength="18"
              :disabled="isView"
            />
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="用户状态" prop="newStatus">
            <ElSelect v-model="form.newStatus" placeholder="请选择用户状态" :disabled="isView">
              <ElOption label="正常" :value="10100" />
              <ElOption label="待审核" :value="10101" />
              <ElOption label="已禁用" :value="10102" />
            </ElSelect>
          </ElFormItem>
        </ElCol>
      </ElRow>

      <ElRow :gutter="20">
        <ElCol :span="24">
          <ElFormItem label="小程序OpenID" prop="wechatXcxOpenid">
            <ElInput
              v-model="form.wechatXcxOpenid"
              placeholder="请输入小程序OpenID"
              :disabled="isView"
            />
          </ElFormItem>
        </ElCol>
      </ElRow>
      <ElRow :gutter="20">
        <ElCol :span="12">
          <ElFormItem label="性别" prop="newGender">
            <ElSelect v-model="form.newGender" placeholder="请选择性别" :disabled="isView">
              <ElOption label="男" :value="10000" />
              <ElOption label="女" :value="10001" />
            </ElSelect>
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="积分数" prop="scoreNum">
            <ElInputNumber
              v-model="form.scoreNum"
              :min="0"
              placeholder="请输入积分数"
              :disabled="isView"
            />
          </ElFormItem>
        </ElCol>
      </ElRow>

      <ElRow :gutter="20">
        <ElCol :span="24">
          <ElFormItem label="用户头像" prop="newHeadPhoto">
            <proUploadImg
              v-model:fileList="headPhotoList"
              action="/api/api/ossFile/saveFile"
              :maxSize="10"
              tip="图片大小不超过10MB"
              :disabled="isView"
            />
          </ElFormItem>
        </ElCol>
      </ElRow>

      <ElRow :gutter="20">
        <ElCol :span="24">
          <ElFormItem label="小程序OpenID" prop="wechatXcxOpenid">
            <ElInput
              v-model="form.wechatXcxOpenid"
              placeholder="请输入小程序OpenID"
              :disabled="isView"
            />
          </ElFormItem>
        </ElCol>
      </ElRow>
    </ElForm>

    <template #footer>
      <div class="dialog-footer">
        <ElButton @click="handleClose">{{ isView ? '关闭' : '取消' }}</ElButton>
        <ElButton v-if="!isView" type="primary" :loading="loading" @click="handleSubmit">
          确定
        </ElButton>
      </div>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
  import { ref, computed, nextTick } from 'vue'
  import { ElMessage } from 'element-plus'
  import type { FormInstance, FormRules } from 'element-plus'
  import { clone } from 'xe-utils'

  // 类型定义
  interface Props {
    modelValue: boolean
    userData?: any | null
  }

  interface Emits {
    (e: 'update:modelValue', value: boolean): void
    (e: 'success'): void
  }

  // Props 和 Emits
  const props = withDefaults(defineProps<Props>(), {
    modelValue: false,
    userData: undefined
  })

  const emit = defineEmits<Emits>()

  // 响应式数据
  const formRef = ref<FormInstance>()
  const loading = ref(false)
  const headPhotoList = ref<any[]>([])

  const initForm = {
    newName: '',
    newPhone: '',
    newIdentity: '',
    newHeadPhoto: '',
    newGender: 10000,
    newStatus: 10100,
    scoreNum: 0,
    wechatXcxOpenid: '',
    disabledFlag: 0
  }

  const form = ref(clone(initForm, true))

  // 计算属性
  const visible = computed({
    get: () => props.modelValue,
    set: (value) => emit('update:modelValue', value)
  })

  const isEdit = computed(() => !!props.userData?.id)
  const isView = computed(() => false) // 可以根据需要添加查看模式

  // 手机号验证函数
  const validatePhone = (rule: any, value: string, callback: any) => {
    if (!value) {
      callback(new Error('请输入手机号'))
      return
    }
    const phoneRegex = /^1[3-9]\d{9}$/
    if (!phoneRegex.test(value)) {
      callback(new Error('请输入正确的手机号'))
      return
    }
    callback()
  }

  // 身份证号验证函数
  const validateIdCard = (rule: any, value: string, callback: any) => {
    if (!value) {
      callback()
      return
    }
    const idCardRegex = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
    if (!idCardRegex.test(value)) {
      callback(new Error('请输入正确的身份证号'))
      return
    }
    callback()
  }

  // 表单验证规则
  const rules: FormRules = {
    newName: [
      { required: true, message: '请输入姓名', trigger: 'blur' },
      { max: 30, message: '姓名不能超过30个字符', trigger: 'blur' }
    ],
    newPhone: [{ required: true, validator: validatePhone, trigger: 'blur' }],
    newIdentity: [{ validator: validateIdCard, trigger: 'blur' }],
    newStatus: [{ required: true, message: '请选择用户状态', trigger: 'change' }],
    newGender: [{ required: true, message: '请选择性别', trigger: 'change' }]
  }

  const handleSubmit = async () => {
    if (!formRef.value) return

    try {
      await formRef.value.validate()

      loading.value = true

      // 处理用户头像
      if (headPhotoList.value.length > 0) {
        form.value.newHeadPhoto = headPhotoList.value[0].url
      }

      // TODO: 调用保存接口
      // await saveNewEmploymentUser({
      //   body: form.value
      // })

      ElMessage.success(isEdit.value ? '编辑成功' : '新增成功')
      emit('success')
    } catch (error) {
      console.error('提交失败:', error)
    } finally {
      loading.value = false
    }
  }

  const handleOpen = () => {
    if (isEdit.value && props.userData) {
      // 编辑模式，回显数据
      if (props.userData.newHeadPhoto) {
        headPhotoList.value = [{ url: props.userData.newHeadPhoto }]
      }
      nextTick(() => {
        form.value = clone(props.userData, true)
      })
    } else {
      // 新增模式，重置表单
      form.value = clone(initForm, true)
      headPhotoList.value = []
    }
  }

  const handleClose = () => {
    formRef.value?.resetFields()
    headPhotoList.value = []
    nextTick(() => {
      visible.value = false
    })
  }
</script>

<style lang="scss" scoped>
  .dialog-footer {
    display: flex;
    gap: 12px;
    justify-content: flex-end;
  }
</style>
